package org.assistant.csp.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.assistant.common.exception.ImplementNotFoundException;
import org.assistant.common.utils.ClassUtils;
import org.assistant.common.web.servlet.mvc.Controller;
import org.assistant.common.web.servlet.mvc.ResultData;
import org.assistant.csp.data.Global;
import org.assistant.csp.data.RelationUser;
import org.assistant.csp.data.UserSession;
import org.assistant.csp.domain.UserDomain;

public class UserController extends Controller {
	private static final long serialVersionUID = -7236332276049620254L;
	private UserDomain userManager;

	public UserController() throws ImplementNotFoundException {
		userManager = ClassUtils.getInterfaceImplement(UserDomain.class);
	}

	protected Object requestDispatcher(HttpServletRequest request,
			HttpServletResponse response, String methodName) {
		try {
			if ("getCurrentUser".equals(methodName)) {
				return getCurrentUser(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取当前用户信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ResultData<?> getCurrentUser(HttpServletRequest request,
			HttpServletResponse response) {
		UserSession userSession = (UserSession) request
			.getSession().getAttribute(Global.CURRENT_USER);
		String userId = userSession.getId();
		String userName = userSession.getName();
		String homeId = userSession.getHomeId();
		String homeName = userSession.getHomeId();
		long roleId = userSession.getRoleId();
		String roleName = userSession.getRoleName();

		StringBuffer buff = new StringBuffer();
		buff.append("{");
		buff.append("id:'").append(userId).append("',");
		buff.append("name:'").append(userName).append("',");
		buff.append("homeId:'").append(homeId).append("',");
		buff.append("homeName:'").append(homeName).append("',");
		buff.append("roleId:'").append(roleId).append("',");
		buff.append("roleName:'").append(roleName).append("',");
		buff.append("}");

		ResultData<?> resultData = new ResultData<String>(buff.toString());

		return resultData;
	}

	private StringBuffer getJsonString(List<RelationUser> list,
			String currentUserId) {
		StringBuffer buff = new StringBuffer();
		if (list == null || list.size() == 0) {
			return buff.append("[]");
		}

		buff.append("[");

		for (int i = 0; i < list.size(); i++) {
			RelationUser user = list.get(i);
			buff.append("{");
			buff.append("'id':");
			buff.append("'").append(user.getId()).append("',");
			buff.append("'name':'").append(user.getName()).append("'");
			if (user.getId().equals(currentUserId)) {
				buff.append(",'currentUser':'").append(true).append("'");
			}
			buff.append("},");
		}

		buff.deleteCharAt(buff.length() - 1);// 删除最后的逗号
		buff.append("]");
		return buff;
	}
}
